// 教师学生控制器
package org.example.backend.controller;

import jakarta.validation.Valid;
import org.example.backend.dto.EvaluationDto;
import org.example.backend.dto.InternshipDetailDto;
import org.example.backend.dto.MaterialReviewDto;
import org.example.backend.dto.PageResponseDto;
import org.example.backend.entity.*;
import org.example.backend.exception.BusinessException;
import org.example.backend.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/teacher")
@CrossOrigin
@PreAuthorize("hasRole('TEACHER')")
public class TeacherStudentController {

    private static final Logger logger = LoggerFactory.getLogger(TeacherStudentController.class);

    private final TeacherService teacherService;
    private final StudentService studentService;
    private final InternshipService internshipService;
    private final UserService userService;
    private final InternshipMaterialService internshipMaterialService;
    private final EvaluationService evaluationService;

    public TeacherStudentController(TeacherService teacherService, StudentService studentService,
                                  InternshipService internshipService, UserService userService,
                                  InternshipMaterialService internshipMaterialService,
                                  EvaluationService evaluationService) {
        this.teacherService = teacherService;
        this.studentService = studentService;
        this.internshipService = internshipService;
        this.userService = userService;
        this.internshipMaterialService = internshipMaterialService;
        this.evaluationService = evaluationService;
    }

    /**
     * 获取指导的学生列表
     */
    @GetMapping("/students")
    public ResponseEntity<PageResponseDto<Student>> getMyStudents(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);

            Page<Student> students = teacherService.getMyStudents(currentUser.getId(), page, size);
            PageResponseDto<Student> response = new PageResponseDto<>(
                    students.getContent(),
                    students.getNumber(),
                    students.getSize(),
                    (int) students.getTotalElements(),
                    students.getTotalPages()
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取指导学生列表失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取学生详细信息
     */
    @GetMapping("/students/{studentId}")
    public ResponseEntity<?> getStudentDetail(@PathVariable Long studentId) {
        try {
            Student student = studentService.getStudentById(studentId);

            Map<String, Object> response = new HashMap<>();
            response.put("student", student);

            // 获取学生的实习信息
            try {
                Internship internship = internshipService.getInternshipByStudentId(studentId);
                response.put("internship", internship);
            } catch (Exception e) {
                // 学生可能还没有实习信息
                response.put("internship", null);
            }

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取学生详细信息失败", e);
            return ResponseEntity.badRequest().body("获取学生信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取学生提交的实习材料列表
     */
    @GetMapping("/students/{studentId}/materials")
    public ResponseEntity<?> getStudentMaterials(
            @PathVariable Long studentId,
            @RequestParam(required = false) Integer type,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 验证学生是否属于自己指导
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);
            Teacher teacher = teacherService.getTeacherByUserId(currentUser.getId());

            // 检查学生是否属于自己指导
            if (teacherService.isMyStudent(teacher.getId(), studentId)) {
                throw new BusinessException("无权限查看该学生的材料");
            }

            Page<InternshipMaterial> materials = internshipMaterialService.getMaterialsByStudent(studentId, type, page, size);
            PageResponseDto<InternshipMaterial> response = new PageResponseDto<>(
                    materials.getContent(),
                    materials.getNumber(),
                    materials.getSize(),
                    (int) materials.getTotalElements(),
                    materials.getTotalPages()
            );

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("获取学生实习材料列表失败", e);
            return ResponseEntity.badRequest().body("获取材料列表失败：" + e.getMessage());
        }
    }

    /**
     * 审阅学生提交的实习材料
     */
    @PutMapping("/materials/review")
    public ResponseEntity<?> reviewMaterial(@Valid @RequestBody MaterialReviewDto reviewDto) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);
            Teacher teacher = teacherService.getTeacherByUserId(currentUser.getId());

            // 执行审阅操作
            InternshipMaterial material = internshipMaterialService.reviewMaterial(
                    reviewDto.getMaterialId(),
                    reviewDto.getStatus(),
                    reviewDto.getRejectReason(),
                    reviewDto.getComment(),
                    teacher.getId()
            );

            Map<String, Object> response = new HashMap<>();
            response.put("message", "材料审阅成功");
            response.put("material", material);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("审阅实习材料失败", e);
            return ResponseEntity.badRequest().body("审阅失败：" + e.getMessage());
        }
    }

    /**
     * 获取待审阅的材料列表
     */
    @GetMapping("/materials/pending")
    public ResponseEntity<?> getPendingMaterials(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);
            Teacher teacher = teacherService.getTeacherByUserId(currentUser.getId());

            Page<InternshipMaterial> materials = internshipMaterialService.getPendingMaterialsByTeacher(
                    teacher.getId(), page, size);
            PageResponseDto<InternshipMaterial> response = new PageResponseDto<>(
                    materials.getContent(),
                    materials.getNumber(),
                    materials.getSize(),
                    (int) materials.getTotalElements(),
                    materials.getTotalPages()
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取待审阅材料列表失败", e);
            return ResponseEntity.badRequest().body("获取待审阅材料列表失败：" + e.getMessage());
        }
    }

    /**
     * 提交学生成绩评定
     */
    @PostMapping("/evaluations")
    public ResponseEntity<?> evaluateStudent(@Valid @RequestBody EvaluationDto evaluationDto) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);
            Teacher teacher = teacherService.getTeacherByUserId(currentUser.getId());

            // 添加调试信息
            boolean isMyStudent = teacherService.isMyStudent(teacher.getId(), evaluationDto.getStudentId());
            logger.info("教师评定权限检查 - 教师ID: {}, 学生ID: {}, 是否为指导学生: {}",
                    teacher.getId(), evaluationDto.getStudentId(), isMyStudent);

            // 验证是否有权限评定该学生
            if (isMyStudent) {
                logger.warn("教师无权限评定该学生 - 教师ID: {}, 学生ID: {}", teacher.getId(), evaluationDto.getStudentId());
                throw new BusinessException("无权限对该学生进行评定");
            }

            // 创建评定记录
            Evaluation evaluation = evaluationService.createEvaluation(evaluationDto, teacher.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "成绩评定成功");
            response.put("evaluation", evaluation);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("成绩评定失败", e);
            return ResponseEntity.badRequest().body("评定失败：" + e.getMessage());
        }
    }


    /**
     * 获取学生的历史评定记录
     */
    @GetMapping("/students/{studentId}/evaluations")
    public ResponseEntity<?> getStudentEvaluations(
            @PathVariable Long studentId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 验证学生是否属于自己指导
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);
            Teacher teacher = teacherService.getTeacherByUserId(currentUser.getId());

            if (teacherService.isMyStudent(teacher.getId(), studentId)) {
                throw new BusinessException("无权限查看该学生的评定记录");
            }

            Page<Evaluation> evaluations = evaluationService.getEvaluationsByStudent(studentId, page, size);
            PageResponseDto<Evaluation> response = new PageResponseDto<>(
                    evaluations.getContent(),
                    evaluations.getNumber(),
                    evaluations.getSize(),
                    (int) evaluations.getTotalElements(),
                    evaluations.getTotalPages()
            );

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("获取学生评定记录失败", e);
            return ResponseEntity.badRequest().body("获取评定记录失败：" + e.getMessage());
        }
    }
    /**
     * 获取教师所有相关的实习列表（已评定和未评定）
     */
    @GetMapping("/internships/all-evaluations")
    public ResponseEntity<?> getAllEvaluations(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);
            Teacher teacher = teacherService.getTeacherByUserId(currentUser.getId());

            Page<InternshipDetailDto> internships = internshipService.getAllEvaluationsByTeacher(
                    teacher.getId(), page, size);

            PageResponseDto<InternshipDetailDto> response = new PageResponseDto<>(
                    internships.getContent(),
                    internships.getTotalElements(),
                    internships.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取教师相关实习列表失败", e);
            return ResponseEntity.badRequest().body("获取教师相关实习列表失败：" + e.getMessage());
        }
    }

}
